import { filter } from "lodash-es";
import { WxFile } from ".";
import util, { dom, scriptAstUtil, LogType, log } from "../util";


export class WxApp extends WxFile {
    constructor(public src: string, public dest: string, public isApp?: Boolean | undefined) {
        super(src, dest, isApp);
    }

    async writeFile(relativePath: string) {
        try {
            const configProps = ['pages', 'window', 'tabBar', 'theme', 'networkTimeout'];
            const uiAppSource = util.readFile(this.dest);

            let { script: { code: scriptCode }, template: { code: templateCode }, style: { code: styleCode } } = dom.getSFC(uiAppSource);
            let uiNode = scriptAstUtil.transform(scriptCode);
            let wxNode = this.script.node;
            let uiConfig = scriptAstUtil.getNodeFromRootByPath(uiNode, 'config');
            let wxConfig = scriptAstUtil.getNodeFromRootByPath(wxNode, 'config');
            let uiData = scriptAstUtil.getNodeFromRootByPath(uiNode, 'data');
            let wxGlobalData = scriptAstUtil.getNodeFromRootByPath(wxNode, 'globalData');
            let uiMounted = scriptAstUtil.getNodeFromRootByPath(uiNode, 'mounted');
            let wxOnReady = scriptAstUtil.getNodeFromRootByPath(wxNode, 'onReady');

            uiConfig.value.properties = filter(wxConfig.value.properties, (prop) => {
                return configProps.indexOf(prop.key.name) > -1;
            });

            if (wxGlobalData) {
                let uiDataProps = uiData.body.body[0].argument.properties;
                for (let i = 0; i < uiDataProps.length; i++) {
                    if (uiDataProps[i].key.name === 'globalData') {
                        uiDataProps[i] = wxGlobalData;
                        break;
                    }
                }
            }

            if (wxOnReady) {
                uiMounted.body = wxOnReady.body;
            }

            let newScriptCode = scriptAstUtil.transformFromAst(uiNode, (code: string) => {
                return code.replace(/getApp\(\)/g, 'ui.getApp()');
            });

            let code = dom.combineCode(templateCode, await newScriptCode, styleCode);
            util.writeFile(this.dest, code);
            log.msg(LogType.WRITE, `${relativePath}`);
            this.copyImages(relativePath);
        }
        catch (err) {
            log.error(`写入${relativePath}失败，${err}`);
        }
    }
}
